﻿using SqlSugar;
using System.Reflection;
using WorkV5APIS.Models;
using WorkV5APIS.Models.NoDBModel;

namespace WorkV5APIS.Common
{
    public static class linkDB
    {

        /// <summary>
        /// 创建链接对象
        /// </summary>
        /// <param name="linkString"></param>
        /// <param name="dbType"></param>
        /// <returns></returns>
        public static SqlSugarClient CreateDB(string linkString, string dbType, bool isFilter = false)
        {

            DbType type = DbType.MySql;
            switch (dbType.ToLower())
            {
                case "mysql":

                    break;
                case "sqlserver":
                    type = DbType.SqlServer;
                    break;
                default:

                    break;
            }

            //创建数据库对象 SqlSugarClient   
            SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = linkString,//连接符字串
                DbType = type, //数据库类型
                IsAutoCloseConnection = true //不设成true要手动close
            });

            //可以指定该db是否添加过滤器
            if (!isFilter)
            {
                db.QueryFilter.Add(new SqlFilterItem()
                {//创建无名称过滤器  所有查询全部都加这个
                    FilterName = null,
                    FilterValue = it =>
                    {
                        //配置假删除条件    省的所有查询都得加上这玩意    如果多租户不分表也可以用这个实现
                        return new SqlFilterResult() { Sql = " isDeleted=0 " };
                    },
                    IsJoinQuery = false //单表查询生效
                });
            }

            //执行回调函数  所有sql都会走这个回调函数
            db.Aop.OnLogExecuting = (sql, pars) =>
            {
                //可以在这里记录log
                // Console.WriteLine(sql);
                //  Console.WriteLine(string.Join(",", pars?.Select(it => it.ParameterName + ":" + it.Value)));//参数

            };


            return db;
        }

        /// <summary>
        /// 创建链接对象
        /// </summary>

        /// <returns></returns>
        public static SqlSugarClient CreateDB()
        {
            string linkString = AppHelper.ReadAppSettings("Settings", "DB0", "value");

            string dbType = AppHelper.ReadAppSettings("Settings", "DB0", "DbType");

            return CreateDB(linkString, dbType); ;
        }

        /// <summary>
        /// 变更数据库表信息
        /// </summary>
        /// <param name="linkString"></param>
        /// <param name="dbType"></param>
        /// <param name="db"></param>
        public static void CodeFirst(SqlSugarClient db = null)
        {
            try
            {
                string codeFirst = AppHelper.ReadAppSettings("Settings", "CodeFirst");
                if (codeFirst.ToLower() != "true")
                {
                    return;
                }

                if (db == null)
                {


                    string linkString = AppHelper.ReadAppSettings("Settings", "DB0", "value");

                    string dbType = AppHelper.ReadAppSettings("Settings", "DB0", "DbType");

                    if (string.IsNullOrEmpty(linkString))
                    {
                        throw new Exception("在未传DB的情况下必须传入链接字符串！");
                    }
                    else
                    {

                        try
                        {
                            db = CreateDB(linkString, dbType);

                        }
                        catch (Exception)
                        {
                            throw new Exception("无法创建链接对象，请检查链接字符串与数据类型！");
                        }

                    }

                }
                //获取当前系统路径
                string rootPath = Directory.GetCurrentDirectory();
                rootPath += "\\Models";
                //读取所有文件
                DirectoryInfo root = new DirectoryInfo(rootPath);
                FileInfo[] files = root.GetFiles();

                foreach (FileInfo file in files)
                {

                    var className = file.Name.Replace(".cs", "");
                    if (className == "S_Base")
                    {
                        continue;
                    }
                    //获取类型
                    Type myType = System.Type.GetType("WorkV5APIS.Models." + className, true);                                      //打印：这是一个无参构造函数


                    //打印：这是一个无参构造函数

                    Console.WriteLine($"更新表{className}");
                    db.CodeFirst.SetStringDefaultLength(200).InitTables(myType);
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }


        }


        /// <summary>
        /// 初始化数据
        /// </summary>
        /// <param name="linkString"></param>
        /// <param name="dbType"></param>
        /// <param name="db"></param>
        public static void DefaultData(SqlSugarClient db = null)
        {
            try
            {
                string codeFirst = AppHelper.ReadAppSettings("Settings", "CodeFirst");
                if (codeFirst.ToLower() != "true")
                {
                    return;
                }

                if (db == null)
                {


                    string linkString = AppHelper.ReadAppSettings("Settings", "DB0", "value");

                    string dbType = AppHelper.ReadAppSettings("Settings", "DB0", "DbType");

                    if (string.IsNullOrEmpty(linkString))
                    {
                        throw new Exception("在未传DB的情况下必须传入链接字符串！");
                    }
                    else
                    {

                        try
                        {
                            db = CreateDB(linkString, dbType);

                        }
                        catch (Exception)
                        {
                            throw new Exception("无法创建链接对象，请检查链接字符串与数据类型！");
                        }

                    }

                }
                S_User s_User = new S_User();
                s_User.UserName = "admin";
                s_User.Password = "123456"; 
                db.Insertable(s_User).ExecuteCommand();

                for (int i = 0; i < 60; i++)
                {
                    Thread.Sleep(100);
                    S_Menu s_Menu = new S_Menu();
                    s_Menu.Name = "用户管理";
                    s_Menu.Icon = "";
                    db.Insertable(s_Menu).ExecuteCommand();
                }
               

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }


        }

    }
}
